<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use DB;
use Exception;

class SPUV implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $tag;

	public $tries = 5;
	public $maxExceptions = 3;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($tag = 'error')
    {
        $this->tag = $tag;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        DB::table('sys_visits')->where('puv', $this->tag)->increment('pv');
        $this->setPUV();
    }

	/**
	 * 任务未能处理
	 *
	 * @param  Exception  $exception
	 * @return void
	 */
	public function failed(Exception $exception)
	{
	    DB::table('job_failed_detail_records')->insert([
	        'tags' => $this->tag,
	        'content' => '',
	        'exception' => $exception->getMessage()
	    ]);
	}

    // 设置PUV记录
    protected function setPUV()
    {
        $ip = request()->ip();
        DB::table('sys_pvs')->insert(['puv' => $this->tag, 'ip' => $ip, 'last_time' => time()]);

        $uv = DB::table('sys_uvs')->where('ip', $ip)->where('lateat', 1)->first('*');
        if ($uv === null) {
            DB::table('sys_uvs')->insert(['puv' => $this->tag, 'ip' => $ip, 'last_time' => time(), 'lateat' => 1]);
            DB::table('sys_visits')->where('puv', $this->tag)->increment('uv');
            return true;
        }

        // if ($uv->last_time + 86400 < time()) {
        if ($uv->last_time + 300 < time()) {
            DB::table('sys_uvs')->where('ip', $uv->ip)->where('puv', $this->tag)->where('lateat', 1)->update(['lateat' => 0]);
            DB::table('sys_uvs')->insert(['puv' => $this->tag, 'ip' => $ip, 'last_time' => time(), 'lateat' => 1]);
            DB::table('sys_visits')->where('puv', $this->tag)->increment('uv');
            return true;
        }

        return 0;
    }
}
